import { useState } from "react";
import { useQuery } from "@tanstack/react-query";

import { fetchTodos } from "./store";

export default function Todos({ initialFilter = "", setEditingIndex }) {
  const [filter, setFilter] = useState(initialFilter);

  const { status, data, isFetching, error, failureCount, refetch } = useQuery({
    queryKey: ["todos", { filter }],
    queryFn: fetchTodos,
  });

  return (
    <div>
      <div>
        <label>
          Filter:{" "}
          <input value={filter} onChange={(e) => setFilter(e.target.value)} />
        </label>
      </div>
      {status === "loading" ? (
        <span>Loading... (Attempt: {failureCount + 1})</span>
      ) : status === "error" ? (
        <span>
          Error: {error.message}
          <br />
          <button onClick={() => refetch()}>Retry</button>
        </span>
      ) : (
        <>
          <ul>
            {data
              ? data.map((todo) => (
                  <li key={todo.id}>
                    {todo.name}{" "}
                    <button onClick={() => setEditingIndex(todo.id)}>
                      Edit
                    </button>
                  </li>
                ))
              : null}
          </ul>
          <div>
            {isFetching ? (
              <span>
                Background Refreshing... (Attempt: {failureCount + 1})
              </span>
            ) : (
              <span>&nbsp;</span>
            )}
          </div>
        </>
      )}
    </div>
  );
}
